import axios from "axios";
import message from "./message";
import eventBus, { useSubscribe } from "../eventBus";
import { getQuery } from ".";

// import { getToken, removeToken } from "./au//th";
let ajaxTokenList = [];

const service = axios.create({
  //后端需要前端传这种头,API出错后就会返回JSON，不然就会返回Html页面
  headers: {
    refactor: true,
    Accept: "application/json, text/javascript, */*; q=0.01",
    "X-Requested-With": "XMLHttpRequest",
  },
  timeout: 100000, // request timeout,
});

//注册取消请求消息
eventBus.subscribe("cancelALlRerquest", () => {
  ajaxTokenList.forEach((cancel, index) => {
    cancel(); //取消请求
    delete ajaxTokenList[index]; //取消后，从缓存内删除
  });
  ajaxTokenList = [];
  //ajaxToken.cancel('canceled');//取消ajax请求
});
/**
 * @description: request interceptor
 * @param {Boolean} noTip 是否不需要加载效果
 * @param {Boolean} isCache 是否需要缓存数据
 * @param {requestBase} requestBase 根据关键字配置不同的域名
 */
service.interceptors.request.use(
  (config) => {
    //给url增加租户前缀
    if (
      window.urlPrefix && //window 存在 urlPrefix 属性
      config.isUrlPrefix !== false && //isUrlPrefix = false时， 不需要自动拼接urlPrefix前缀
      config.url.indexOf("http") !== 0 && //请求url不是http开头
      config.url.indexOf("https") !== 0 && //请求url不是https开头
      config.url.indexOf(window.urlPrefix) !== 0 //请求url未拼接 urlPrefix
    ) {
      config.url = window.urlPrefix + config.url;
    }

    //给headers增加token信息
    if (
      window.csrfToken && //存在 csrfToken
      config.headers?.["X-CSRF-Token"] === undefined && //并且配置未带 csrfToken
      config.isCsrfToken !== false //也可以手动设置不增加token
    ) {
      config.headers["X-CSRF-Token"] = window.csrfToken;
    }

    if (config.needCancelToken === true) {
      // noCancelToken = true 不需要做请求缓存
      config.cancelToken = new axios.CancelToken((cancel) => {
        ajaxTokenList.push(cancel);
        config.__cancelToken__ = cancel;
      }); //给请求增加取消标记
    }

    // config.headers["Authorization"] = "Bearer " + getToken();
    // 防止缓存，GET请求默认带_t参数
    if (config.method === "get") {
      config.params = {
        ...config.data,
        // ...{ '__randNum': new Date().getTime() }
      };
    }
    if (config.isForm) {
      config.headers["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";
    } else {
      config.headers["Content-Type"] = "application/json;charset=utf-8";
    }

    const query = getQuery();
    if (query.print_html_to_pdf&& config.url.indexOf('/flowinstance/approval/get-process-preview') != -1) {
      if (config.url.indexOf("?") != -1) {
        config.url += "&print_html_to_pdf=" + query.print_html_to_pdf;
      } else {
        config.url += "?print_html_to_pdf=" + query.print_html_to_pdf;
      }
    }

    return config;
  },
  (error) => {
    console.warn(error); // for debug
    return Promise.reject(error);
  }
);
const messageTipCode = [0, -10, 1000, 10000, 30000, 30050, 30013, 31001, 31002, 30014, 31003, 31004, 31005, 31006, 31007, 31008, 31009, 31012, 31010, 31011, 31012, 31013, 31020, 32001, 90000];
const messageSueeessTipCode = [1]; //不需要在公共请求内给出提示的code
// response interceptor
service.interceptors.response.use(
  (response) => {
    let index = ajaxTokenList.findIndex((cancel) => {
      return cancel === response.config.__cancelToken__;
    }); //得到当前请求在cancel数组内的索引
    ajaxTokenList.splice(index, 1); //请求成功后，删除当前请求的cancel缓存

    // IE 8-9 workaround
    if (response.data === null && response.config.responseType === "json" && response.request.responseText !== null) {
      try {
        // eslint-disable-next-line no-param-reassign
        response.data = JSON.parse(response.request.responseText);
      } catch (e) {
        // ignored
      }
    }

    if (response?.config?.noTip !== true) {
      let data = response.data;
      if (data.code === -3) {
        let pathname=window.location.pathname;
        //登录超时
        message.info({
          content: "页面已超时，请重新登录！",
          afterClose: function () {
            if (~pathname.indexOf("/platform-manage")) {
              //系统管理模块
              window.location.href = "/platform-manage/login?backurl=" + encodeURIComponent(window.location.href); //系统管理模块的界面，跳转到登录页
            } else {
              window.top.location.reload();
            }
          },
        });

      } else if (data.code === 10002) {
        message.info({
          content: data.message,
          afterClose: function () {
            window.top.location.reload();
          },
        });
        return Promise.reject(response.data);
      } else if (data.code === 34001) {
        //接口返回是否选择，要用户再次确认后，才实际发出请求
        return response;
      } else if (data.code === -11 || data.code === -1) {
        //弹窗异常友好页面（包含其他详细信息）
        message.info({
          content: "<div>" + data.message+ "</div><div>" + data.errorinfo + "</div>",
        });
      } else if (data.code === 2) {
        //签章密码验证错误时，不用给公共提示反馈
      }else if(messageSueeessTipCode.indexOf(data.code) < 0) {  
        message.info({
          content: data.message || "未知错误",
        });
      }
    }

    //fixme: 这里后续处理，php接口报错会返回一段HTML
    if (response.headers["content-type"] === "text/html; charset=UTF-8") {
      return Promise.reject(response.data);
    }

    const res = response.data;
    // for 用于本地调试登录获取token值
    // if (res.access_token) return res;
    if (res.error) return;
    return res;
  },
  (error, b) => {
    let index = ajaxTokenList.findIndex((cancel) => {
      return cancel === error.config.__cancelToken__;
    });
    ajaxTokenList.splice(index, 1); //请求失败后，删除当前请求的cancel缓存
    return Promise.reject(error);
  }
);

export default service;
